package com.kancy.publicapi.web.controller;

import com.kancy.publicapi.aop.annotation.NotPrintLog;
import com.kancy.publicapi.common.util.DateUtils;
import com.kancy.publicapi.common.util.PathUtils;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.util.Date;

/**
 * @author kancy
 * @date 2019/12/23 11:36
 **/
@RestController
@Slf4j
@RequiredArgsConstructor
public class FileController {

    @NotPrintLog
    @RequestMapping("/file/upload")
    public String upload (@RequestParam("file") MultipartFile file) {
        File dest = createNewFile(file);
        try {
            // 保存到服务器中
            file.transferTo(dest);
            return String.format("%s 文件上传成功", file.getOriginalFilename());
        } catch (Exception e) {
            e.printStackTrace();
        }
        return String.format("%s 文件上传失败", file.getOriginalFilename());
    }

    private File createNewFile(MultipartFile file) {
        // 文件重命名，防止重复
        String fileName = String.format("%s/%s/%s_%s",
                PathUtils.getUploadPath(), DateUtils.dateToString(new Date(), DateUtils.DATE_PATTERN_YYMMDD),
                DateUtils.dateToString(new Date(), DateUtils.DATE_PATTERN_HHMMSS),file.getOriginalFilename()
        );
        File dest = new File(fileName);
        // 判断路径是否存在，如果不存在则创建
        if(!dest.getParentFile().exists()) {
            dest.getParentFile().mkdirs();
        }
        return dest;
    }
}
